package com.ocean.linkedlist;

/**
 * https://leetcode.cn/problems/reverse-nodes-in-k-group/
 */
public class ReverseNodesInKGroup4 {

    public static void main(String[] args) {
        ListNode e5 = new ListNode(5, null);
        ListNode e4 = new ListNode(4, e5);
        ListNode e3 = new ListNode(3, e4);
        ListNode e2 = new ListNode(2, e3);
        ListNode e1 = new ListNode(1, e2);
        ListNode.print(e1);
        ListNode reverse = new ReverseNodesInKGroup4().reverseKGroup(e1, 4);
        ListNode.print(reverse);
    }

    public ListNode reverseKGroup(ListNode head, int k) {
        if (k == 1 || head.next == null) {
            return head;
        }
        ListNode dummy = new ListNode();
        dummy.next = head;
        ListNode temp = dummy;
        while (temp.next != null) {
            // 拿到k个
            // 先把上一组的尾结点记下来
            ListNode last = temp;
            for (int i = 0; i < k && temp != null; i++) {
                temp = temp.next;
            }
            if (temp == null) {
                break; // 不足k个
            }
            // 下一组的头节点
            ListNode next = temp.next;

            temp.next = null;
            // 这一组的头节点
            ListNode curFirst = last.next;
            // 反转这一组 // 将上一组的尾部链接到反转后的头部
            last.next = reverse(curFirst);
            // 这一组的头要链接上下一组的尾部
            curFirst.next = next;
            // 更新temp
            temp = curFirst;
        }
        return dummy.next;

    }

    public ListNode reverse(ListNode head) {
        ListNode temp = head;
        ListNode cur = null;
        while (temp != null) {
            ListNode next = temp.next;
            temp.next = cur;
            cur = temp;
            temp = next;
        }
        return cur;
    }
}
